package com.dy.web.controller.system;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson2.JSON;
import com.dy.common.utils.StringUtils;
import com.dy.common.utils.bean.BeanUtils;
import com.dy.framework.config.mqtt.MqttAcceptClient;
import com.dy.framework.config.mqtt.MqttSendClient;
import com.dy.system.domain.FreshMedicalMachine;
import com.dy.system.domain.MedicalInstitution;
import com.dy.system.domain.vo.FreshMedicalMachineVo;
import com.dy.system.domain.vo.WarningMessageVo;
import com.dy.system.service.IFreshMedicalMachineService;
import com.dy.system.service.IMedicalEquipmentReportLogService;
import com.dy.system.service.IMedicalInstitutionService;
import com.github.pagehelper.PageHelper;
import org.aspectj.weaver.loadtime.Aj;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import com.dy.common.annotation.Log;
import com.dy.common.core.controller.BaseController;
import com.dy.common.core.domain.AjaxResult;
import com.dy.common.enums.BusinessType;
import com.dy.common.utils.poi.ExcelUtil;
import com.dy.common.core.page.TableDataInfo;

/**
 * 设备信息Controller
 *
 * @author ruoyi
 * @date 2022-08-16
 */
@RestController
@RequestMapping("/system/freshMachine")
public class FreshMedicalMachineController extends BaseController {
    @Autowired
    private IFreshMedicalMachineService freshMedicalMachineService;
    @Autowired
    private IMedicalInstitutionService medicalInstitutionService;
    @Autowired
    private MqttSendClient MqttSendClient;
    @Autowired
    private MqttAcceptClient mqttAcceptClient;

    @Autowired
    private IMedicalEquipmentReportLogService medicalEquipmentReportLogService;


    /***
     * 设备命令操作
     * @param code
     * @param command
     * @param commandValue
     * @return
     */
    @PostMapping("/op/medical")
    public AjaxResult opMedical(@RequestParam String code,@RequestParam String command,@RequestParam String commandValue){
        //发送消息
        Map<String,Object> writeDataMap = new HashMap<>();
        writeDataMap.put("Unix",System.currentTimeMillis());
        writeDataMap.put("Version","V1.0");
        Map<String,Object> medicalMap = new HashMap<>();
        Map<String,Object> commandMap = new HashMap<>();
        commandMap.put(command,commandValue);
        medicalMap.put("RXDQ",commandMap);
        writeDataMap.put("Write_Data",medicalMap);
        logger.info("accessDataMap ={}",JSON.toJSONString(writeDataMap));
        MqttSendClient.publish(false,code+"12345678/access_data", JSON.toJSONString(writeDataMap));
        return toAjax(true);
    }


    /***
     * 设备列表 applet
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping("/medical/list")
    public AjaxResult getMedicalDataList(@RequestParam Integer pageNo, @RequestParam Integer pageSize,
                                         Integer status,String searchValue){

        PageHelper.startPage(pageNo,pageSize,"id desc");
        FreshMedicalMachine machine = new FreshMedicalMachine();
        if (status != null){
            machine.setRunningStatus(String.valueOf(status));
        }
        if (StringUtils.isNotBlank(searchValue)){
            //查询机构信息
            MedicalInstitution institution = new MedicalInstitution();
            institution.setName(searchValue);
            List<MedicalInstitution> list = medicalInstitutionService.selectMedicalInstitutionList(institution);
            if (!CollectionUtils.isEmpty(list)){
                List<Long> idList = list.stream().map(m -> m.getId()).collect(Collectors.toList());
                machine.setMedicalIdList(idList);
            }else{
                machine.setMachineCode(searchValue);
            }
        }
        List<FreshMedicalMachine> machineList = freshMedicalMachineService.selectFreshMedicalMachineList(machine);
        List<FreshMedicalMachineVo> voList = new ArrayList<>();
        String img = "https://dyep.cc/prod-api";
        machineList.forEach(m ->{
            MedicalInstitution institution = medicalInstitutionService.selectMedicalInstitutionById(m.getInstitutionId());
            if (institution == null){
                return;
            }
            //总处理量
            Integer jgzcll = medicalEquipmentReportLogService.getMedicalHandleData(null,m.getId(),m.getMachineCode());
            FreshMedicalMachineVo machineVo = BeanUtils.generatorObject(m, FreshMedicalMachineVo.class);
            machineVo.setTotalHandle(String.valueOf(jgzcll));
            //日处理量
            Integer zuotianHandle = medicalEquipmentReportLogService.getMedicalHandleData("zuotian",null,m.getMachineCode());
            Integer jintianHandle = medicalEquipmentReportLogService.getMedicalHandleData("jintian",null,m.getMachineCode());
            Integer fresh = jintianHandle >= zuotianHandle ? jintianHandle - zuotianHandle : 0;
            machineVo.setDayTotalHandle(String.valueOf(fresh));

            machineVo.setMedicalIdName(institution.getName());
            machineVo.setOpCode(StringUtils.isNoneBlank(machineVo.getOpCode()) ? img + machineVo.getOpCode() : "");
            voList.add(machineVo);
        });
        return AjaxResult.success(voList);
    }


    /***
     * 根据查询单个设备信息
     * @param id
     * @return
     */
    @GetMapping("/medical/info")
    public AjaxResult getMedicalData(@RequestParam Long id){
        FreshMedicalMachine machine = freshMedicalMachineService.selectFreshMedicalMachineById(id);
        if (machine != null){
            MedicalInstitution institution = medicalInstitutionService.selectMedicalInstitutionById(machine.getInstitutionId());
            if (institution != null){
                machine.setMedicalIdName(institution.getName());
            }
            //总处理量
            Integer jgzcll = medicalEquipmentReportLogService.getMedicalHandleData(null,null,machine.getMachineCode());
            machine.setTotalHandle(String.valueOf(jgzcll));
            //日处理量
            Integer zuotianHandle = medicalEquipmentReportLogService.getMedicalHandleData("zuotian",null,machine.getMachineCode());
            Integer jintianHandle = medicalEquipmentReportLogService.getMedicalHandleData("jintian",null,machine.getMachineCode());
            Integer fresh = jintianHandle >= zuotianHandle ? jintianHandle - zuotianHandle : 0;
            machine.setDayTotalHandle(String.valueOf(fresh));

            String img = "https://dyep.cc/prod-api";
            machine.setOpCode(StringUtils.isNoneBlank(machine.getOpCode()) ? img + machine.getOpCode() : "");

        }
        return AjaxResult.success(machine);
    }


    /**
     * 查询设备信息列表
     */
    @PreAuthorize("@ss.hasPermi('system:freshMachine:list')")
    @GetMapping("/list")
    public TableDataInfo list(FreshMedicalMachine freshMedicalMachine) {
        if (StringUtils.isNotBlank(freshMedicalMachine.getMedicalIdName())){
            MedicalInstitution institution = new MedicalInstitution();
            institution.setName(freshMedicalMachine.getMedicalIdName());
            List<MedicalInstitution> institutionList = medicalInstitutionService.selectMedicalInstitutionList(institution);
            if (!CollectionUtils.isEmpty(institutionList)){
                List<Long> medicalIdList = institutionList.stream().map(e -> e.getId()).collect(Collectors.toList());
                freshMedicalMachine.setMedicalIdList(medicalIdList);
            }
        }
        startPageOrderBy("id desc");
        List<FreshMedicalMachine> list = freshMedicalMachineService.selectFreshMedicalMachineList(freshMedicalMachine);
        String img = "https://dyep.cc/prod-api";
        list.forEach(medicalMachine ->{
            MedicalInstitution institution = medicalInstitutionService.selectMedicalInstitutionById(medicalMachine.getInstitutionId());
            if (institution != null){
                medicalMachine.setMedicalIdName(institution.getName());
            }
            medicalMachine.setOpCode(StringUtils.isNoneBlank(medicalMachine.getOpCode()) ? img + medicalMachine.getOpCode() : "");
        });
        return getDataTable(list);
    }

    /**
     * 导出设备信息列表
     */
    @PreAuthorize("@ss.hasPermi('system:freshMachine:export')")
    @Log(title = "设备信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, FreshMedicalMachine freshMedicalMachine) {
        List<FreshMedicalMachine> list = freshMedicalMachineService.selectFreshMedicalMachineList(freshMedicalMachine);
        ExcelUtil<FreshMedicalMachine> util = new ExcelUtil<FreshMedicalMachine>(FreshMedicalMachine.class);
        util.exportExcel(response, list, "设备信息数据");
    }

    /**
     * 获取设备信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:freshMachine:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(freshMedicalMachineService.selectFreshMedicalMachineById(id));
    }


    public static void main(String[] args) {
        String str = "1-3-33-1";
        System.out.println(str.replace("-",""));
    }
    /**
     * 新增设备信息
     */
    @PreAuthorize("@ss.hasPermi('system:freshMachine:add')")
    @Log(title = "设备信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody FreshMedicalMachine freshMedicalMachine) {
        String machineCode = freshMedicalMachine.getMachineCode();
        String replace = machineCode.replace("-","");
        freshMedicalMachine.setMachineCode(replace);
        FreshMedicalMachine machine = freshMedicalMachineService.selectMedicalMachineByCode(freshMedicalMachine.getMachineCode());
        if (machine != null){
            return AjaxResult.error("新增设备'" + freshMedicalMachine.getMachineCode() + "'失败，设备已存在");
        }
        int count = freshMedicalMachineService.insertFreshMedicalMachine(freshMedicalMachine);
        String topicName = freshMedicalMachine.getMachineCode()+"12345678/pub_data";
        logger.info("subscribe topicName ={}",topicName);
        mqttAcceptClient.subscribe(topicName,0);
        //发送消息
        Map<String,Object> accessDataMap = new HashMap<>();
        accessDataMap.put("Unix",System.currentTimeMillis());
        accessDataMap.put("Version","V1.0");
        accessDataMap.put("Content","alldata");
        logger.info("accessDataMap ={}",JSON.toJSONString(accessDataMap));
        MqttSendClient.publish(false,freshMedicalMachine.getMachineCode()+"12345678/access_data", JSON.toJSONString(accessDataMap));
        return toAjax(count);
    }

    /**
     * 修改设备信息
     */
    @PreAuthorize("@ss.hasPermi('system:freshMachine:edit')")
    @Log(title = "设备信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody FreshMedicalMachine freshMedicalMachine) {
        return toAjax(freshMedicalMachineService.updateFreshMedicalMachine(freshMedicalMachine));
    }

    /**
     * 删除设备信息
     */
    @PreAuthorize("@ss.hasPermi('system:freshMachine:remove')")
    @Log(title = "设备信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(freshMedicalMachineService.deleteFreshMedicalMachineByIds(ids));
    }
}
